﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Wicresoft.RDW.Presentation;
using Wicresoft.RDW.Utility;
using System.Web.Security;


namespace Wicresoft.RDW.Feedback
{
    public partial class Send : BasePage
    {
        protected int i = 1;

        public override void InitControlResource()
        {
            if (CurrentUserId == 0)
            {
                if (string.Equals(GetQueryString("language"), Utility.Language.EN.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    this.Page.Culture = "en-US";
                    this.Page.UICulture = "en-US";
                    Language = Utility.Language.EN;
                }
                else
                {
                    this.Page.Culture = "zh-CN";
                    this.Page.UICulture = "zh-CN";
                    Language = Utility.Language.CN;
                }
            }
            var visitRequest = VisitRequestPresent.GetById(Id);
            if (visitRequest != null)
            {
                var feedback = FeedbackPresent.GetByCondition(q => q.RequestId == visitRequest.RequestId);
                if (feedback.Status == (int)FeedbackStatus.Completed)
                {
                    PageStatus = PageStatus.Readonly;
                    lbtnReturn.Visible = true;
                    lbtnSubmit.Visible = false;
                    lbtnCancel.Visible = false;
                }
                else
                {
                    PageStatus = PageStatus.New;
                    lbtnReturn.Visible = false;
                }
                var request = RequestPresent.GetById(visitRequest.RequestId);
                lblVisitDepartment.Text = visitRequest.CompanyName;
                var accompanyUser = UserPresent.GetById((int)visitRequest.Accompany);
                if (request != null)
                {
                    lblRequestDate.Text = request.RequestDate.ToShortDateString();
                    var requestUser = UserPresent.GetById(request.RequestUserId);
                    if (requestUser != null)
                    {
                        if (feedback.Status != (int)FeedbackStatus.Completed && CurrentUserId != requestUser.UserId)
                        {
                            FormsAuthentication.RedirectToLoginPage();
                        }
                        lblRequestName.Text = Language.ToString() == "CN" ? requestUser.NameCN : requestUser.NameEN;

                        lblRequestDepartment.Text = requestUser.BD;
                        var RequestMobile = string.IsNullOrEmpty(requestUser.Mobile) ? "--" : requestUser.Mobile;
                        var RequestOfficePhone = string.IsNullOrEmpty(requestUser.OfficePhone) ? "--" : requestUser.OfficePhone;
                        var RequestEmail = string.IsNullOrEmpty(requestUser.Email) ? "--" : requestUser.Email;
                        lblRequestTel.Text = RequestMobile + "，" + RequestOfficePhone + "，" + RequestEmail;
                    }
                }
                if (accompanyUser != null)
                {
                    lblAccompanyName.Text = Language.ToString() == "CN" ? accompanyUser.NameCN : accompanyUser.NameEN;

                    lblAccompanyDepartment.Text = accompanyUser.BD;
                    var AccompanyMobile = string.IsNullOrEmpty(accompanyUser.Mobile) ? "--" : accompanyUser.Mobile;
                    var AccompanyOfficePhone = string.IsNullOrEmpty(accompanyUser.OfficePhone) ? "--" : accompanyUser.OfficePhone;
                    var AccompanyEmail = string.IsNullOrEmpty(accompanyUser.Email) ? "--" : accompanyUser.Email;
                    lblAccompanyTel.Text = AccompanyMobile + "，" + AccompanyOfficePhone + "，" + AccompanyEmail;
                }
                lbtnSubmit.Text = Resources.NameResource.btnSubmit;
                lbtnReturn.Text = Resources.NameResource.lbtnReturn;
                lbtnCancel.Text = Resources.NameResource.btnCancel;

                if (PageStatus == PageStatus.Readonly)
                {
                    var feedbackAnswer = FeedbackAnswerPresent.GetList(p => p.FeedbackId == feedback.FeedbackId);
                    var qus = QusetionPresent.GetList();

                    var questionList = (from q in qus
                                        join f in feedbackAnswer on q.QuestionId equals f.QuestionId
                                        select q).ToList();

                    dlFeedbackQuestion.DataSource = questionList;
                }
                else
                {
                    dlFeedbackQuestion.DataSource = QusetionPresent.GetList(p => p.Status == (int)QuestionStatus.Active);
                }
                dlFeedbackQuestion.DataBind();
            }
            else
            {
                phBody.Visible = false;
            }
        }

        protected void dlFeedbackQuestion_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Model.Question question = e.Item.DataItem as Model.Question;
                RadioButtonList rbtnlAnswer = e.Item.FindControl("rbtnlAnswer") as RadioButtonList;

                rbtnlAnswer.DataSource = GetAnswertData(question.QuestionId);
                if (PageStatus == PageStatus.Readonly)
                {
                    var visitrequest = VisitRequestPresent.GetById(Id);
                    var feedbackId = FeedbackPresent.GetByCondition(q => q.RequestId == visitrequest.RequestId);
                    var feedbackAnswer = FeedbackAnswerPresent.GetByCondition(p => p.QuestionId == question.QuestionId && p.FeedbackId == feedbackId.FeedbackId);

                    var answer = AnswerPresent.GetById((int)feedbackAnswer.AnswerId);
                    if (Language.ToString() == "CN")
                    {
                        rbtnlAnswer.SelectedValue = answer.Answer_CN;
                    }
                    else
                    {
                        rbtnlAnswer.SelectedValue = answer.Answer_EN;
                    }
                    rbtnlAnswer.Enabled = false;
                }
                RequiredFieldValidator rfvFeedback = e.Item.FindControl("rfvFeedback") as RequiredFieldValidator;
                rfvFeedback.ErrorMessage = Resources.NameResource.rfvFeedback;
                rbtnlAnswer.DataBind();
            }
        }

        private List<string> GetAnswertData(int questionID)
        {
            var answerList = AnswerPresent.GetAnswerList(questionID);
            var answerName = new List<string>();

            if (Language.ToString() == "CN")
            {
                var cn = answerList.Select(p => p.Answer_CN);
                answerName.AddRange(cn);
            }
            else
            {
                var en = answerList.Select(p => p.Answer_EN);
                answerName.AddRange(en);
            }
            return answerName;
        }

        protected void lbtnSubmit_Click(object sender, EventArgs e)
        {
            string answerName;
            int answerID;
            var visitrequest = VisitRequestPresent.GetById(Id);
            var feedback = FeedbackPresent.GetByCondition(q => q.RequestId == visitrequest.RequestId);
            if (feedback != null)
            {
                if (feedback.Status == (int)FeedbackStatus.Active)
                {
                    var requestCredit = RequestPresent.GetById(feedback.RequestId);
                    var user = UserPresent.GetById(requestCredit.RequestUserId);
                    if (user.DepId != null)
                    {
                        var department = DepartmentPresent.GetById((int)user.DepId);
                        if (department != null)
                        {
                            if (department.CreditScore < int.Parse(SysSettingPresent.MaxCreditScore))
                            {
                                department.CreditScore += 1;
                            }
                            else
                            {
                                department.CreditScore = int.Parse(SysSettingPresent.MaxCreditScore);
                            }
                            DepartmentPresent.Update(department);
                        }
                    }
                }
                var questionList = QusetionPresent.GetList(p => p.Status == (int)QuestionStatus.Active);
                for (int i = 0; i < dlFeedbackQuestion.Items.Count; i++)
                {
                    RadioButtonList rbl = dlFeedbackQuestion.Items[i].FindControl("rbtnlAnswer") as RadioButtonList;

                    answerName = rbl.SelectedValue;
                    int questionId = questionList[i].QuestionId;
                    if (Language.ToString() == "CN")
                    {
                        var answer = AnswerPresent.GetByCondition(p => p.QuestionId == questionId && p.Answer_CN == answerName);
                        answerID = answer.Id;
                    }
                    else
                    {
                        var answer = AnswerPresent.GetByCondition(p => p.QuestionId == questionId && p.Answer_EN == answerName);
                        answerID = answer.Id;
                    }

                    Model.FeedbackAnswer feedbackAnswer = new Model.FeedbackAnswer()
                         {
                             QuestionId = questionId,
                             AnswerId = answerID,
                             FeedbackId = feedback.FeedbackId
                         };
                    FeedbackAnswerPresent.Create(feedbackAnswer);
                }

                feedback.Status = (int)FeedbackStatus.Completed;
                FeedbackPresent.Update(feedback);
            }

            Response.Redirect("View.aspx");
        }

        protected void lbtnReturn_Click(object sender, EventArgs e)
        {
            Response.Write("<script language=javascript>history.go(-2);</script>");
        }
        protected void lbtnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("Send.aspx?id=" + Id);
        }

    }
}